﻿/*!
 * 检查预约V2
 * 2017-04-19
 */

var Schedule = function (scheduleType, relativeUrl) {
    //相对路径
    this.relativeUrl = relativeUrl;
    //预约类型
    this.scheduleType = scheduleType;
    //孕周天数
    this.pregnantDays = null;
    //开始日期
    var now = new Date();

    this.IgnoreScheduleFlag = false;

    this.startDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();

    this.localSartDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    //申请单列表
    this.examRequestList = [];
    //病人列表
    this.patientList = [];
    //检查申请单查询条件
    this.queryCondition = imcis.parseURL(location.href).params;
    if ($("#hdnParamsJsonString").val()) {
        this.queryCondition=JSON.parse($("#hdnParamsJsonString").val());
    }
    this.scheduleOperatorID = this.queryCondition.ScheduleOperatorID;
    this.scheduleOperatorName = this.queryCondition.ScheduleOperatorName;
};
//alert 提示框 callback 可有可无，有的时候点确认调用
 Schedule.prototype.alert = function (msg, callback) {
     if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        layer.open({
            content: msg
            , btn: '确定'
            , yes: function (index) {
                if (callback) {
                    callback();
                }
                layer.closeAll('dialog');
            }
        });
    } else {
        var h = Math.ceil(msg.length / 18);
        h = 200 + (h == 1 ? 0 : h * 18);
        layer.confirm(msg, {
            btn: ['确定'], //按钮
            area: ['410px', h + 'px'],
            title: '提示',
        }, function () {
            if (callback) {
                callback();
            }
            layer.closeAll('dialog');
        });
    }
};

//提示框 tips 1S之后会自动消失
 Schedule.prototype.tips = function (msg) {
     if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        layer.open({
            content: msg
           , skin: 'msg'
           , time: 0.5 
        });
    } else {
        layer.msg(msg);
    }
};

//确认msg callback按确认 调用
 Schedule.prototype.comfirm = function (msg, yescallback, nocallback) {  
    if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
            layer.open({
                content: msg
              , btn: ['确定', '取消']
              , yes: function (index) {
                  if (yescallback) {
                      yescallback();
                  }
                  layer.close(index);
              }
              , no: function(index){
                if(nocallback) {
                    nocallback();
                }
                layer.close(index);
              }
            });
    } else {
        var h = Math.ceil(msg.length / 18); 
        h = 200 + (h == 1 ? 0 : h * 18);
        layer.confirm(msg, {
            btn: ['确定', '取消'], //按钮
            area: ['400px', h + 'px']
        }, function () {
            if (yescallback) {
                yescallback();
            }
            layer.closeAll('dialog');
        }, function () {
            layer.closeAll('dialog');
            return false;
        })
    }

};

//确认msg callback按确认 调用
Schedule.prototype.comfirmOnlyYes = function (msg, callback) {
    if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        layer.open({
            content: msg
            , btn: ['确定']
            , yes: function (index) {
                if (callback) {
                    callback();
                }
                layer.close(index);
            }
        });
    } else {
        layer.confirm(msg, {
            btn: ['确定'], //按钮
            area: ['400px', '200px']
        }, function () {
            if (callback) {
                callback();
            }
            layer.closeAll('dialog');
        }, function () {
            layer.closeAll('dialog');
            return false;
        })
    }

};

//确认msg callback按确认 调用
Schedule.prototype.comfirmSearch = function (msg, yescallback, nocallback) {
    if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        layer.open({
            content: msg
            , btn: ['查询', '取消']
            , yes: function (index) {
                if (yescallback) {
                    yescallback();
                }
                layer.close(index);
            }
            , no: function (index) {
                if (nocallback) {
                    nocallback();
                }
                layer.close(index);
            }
        });
    } else {
        var h = Math.ceil(msg.length / 18);
        h = 200 + (h == 1 ? 0 : h * 18);
        layer.confirm(msg, {
            btn: ['查询', '取消'], //按钮
            area: ['400px', h + 'px']
        }, function () {
            if (yescallback) {
                yescallback();
            }
            layer.closeAll('dialog');
        }, function () {
            layer.closeAll('dialog');
            return false;
        })
    }

};

Schedule.prototype.prompt = function (title, placeholder, yescallback, nocallback) {
    if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        layer.open({
            content: '<div class="layui-m-layercont-div"><input type="text" class="form-control" placeholder="' + placeholder + '"></div>'
            , btn: ['确定', '取消']
            , yes: function (index) {
                var val = $('.layui-m-layer[index="' + index + '"] input').val();
                if (yescallback) {
                    yescallback(val);
                }
                layer.close(index);
            }
            , no: function (index) {
                if (nocallback) {
                    nocallback();
                }
                layer.close(index);
            }
        });
    } else {
        layer.prompt({
            formType: 2,
            value: val,
            title: title,
            area: ['800px', '350px'] //自定义文本域宽高
        }, function (value, index, elem) {
            if (callback) {
                callback(value, index, elem);
            }
            layer.closeAll('dialog');
        });
    }
};

Schedule.prototype.promptToExamMobile = function (title, placeholder, yescallback, nocallback) {
    var html = '<div class="tip-title">' + title + '</div>' +
        '<div class="layui-m-layercont-div">' +
        '<span class="icon-required">*</span><input type="text" class="form-control" placeholder="' + placeholder + '">' +
        '<div class="tip-note">存为预设可在《设置》中设置进入网页的默认查询条件</div>' +
        '</div>';
              
    layer.open({
        content: html
        , btn: ['确定', '取消']
        , yes: function (index) {
            var val = $('.layui-m-layer[index="' + index + '"] input').val();
            if (yescallback) {
                yescallback(val);
            }
            layer.close(index);
        }
        , no: function (index) {
            if (nocallback) {
                nocallback();
            }
            layer.close(index);
        }
    });
};

//loading加载
Schedule.prototype.loading = function () {
    if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        layer.open({ type: 2,time:1 });
    } else {
        this.loadingModel = layer.load(1, { shade: [0.4, '#333'] });
    }
    
};
//removeLoading 去掉加载
Schedule.prototype.removeLoading = function () {
    if (this.scheduleType == 'Mobile' || this.scheduleType == 'Pad') {
        return false;
    } else {
        layer.close(this.loadingModel);
    }

};

//检查申请单里的Json格式时间转为字符串格式
Schedule.transExamRequestDatetime = function (req) {
    req.AdmitDate = imcis.convertDateFromJson(req.AdmitDate);
    req.AuditDate = imcis.convertDateFromJson(req.AuditDate);
    req.BirthDate = imcis.convertDateFromJson(req.BirthDate);
    req.ConsultEndDate = imcis.convertDateFromJson(req.ConsultEndDate);
    req.ConsultRequestDate = imcis.convertDateFromJson(req.ConsultRequestDate);
    req.CreateDate = imcis.convertDateFromJson(req.CreateDate);
    req.DischargeDate = imcis.convertDateFromJson(req.DischargeDate);
    req.ObservationDate = imcis.convertDateFromJson(req.ObservationDate);
    req.ObservationEndDate = imcis.convertDateFromJson(req.ObservationEndDate);
    req.PreliminaryDate = imcis.convertDateFromJson(req.PreliminaryDate);
    req.RegTime = imcis.convertDateFromJson(req.RegTime);
    req.RequestedDate = imcis.convertDateFromJson(req.RequestedDate);
    req.ResultDate = imcis.convertDateFromJson(req.ResultDate);
    req.ResultPrintTime = imcis.convertDateFromJson(req.ResultPrintTime);
    req.ReviseDate = imcis.convertDateFromJson(req.ReviseDate);
    req.ScheduleEndDate = imcis.convertDateFromJson(req.ScheduleEndDate);
    req.ScheduleStartDate = imcis.convertDateFromJson(req.ScheduleStartDate);
    req.ScheduledDate = imcis.convertDateFromJson(req.ScheduledDate);

    return req;
}

//显示孕周对话框callback
Schedule.prototype.showPregnantDays = function (callback, examRequest) {
    var that = this;
    var keybord_html = ''
    var area = ['500px', '300px'];
    if (this.scheduleType == "Mobile") {
     area = ['300px','210px'];
    }
    if (this.scheduleType == "Self") {
        area = ['500px', '600px']
        keybord_html = '<div id="keybord">' +
                               '<div class="keybord_item">1</div>' +
                                   '<div class="keybord_item">2</div>' +
                                   '<div class="keybord_item">3</div>' +
                                   '<div class="keybord_item">4</div>' +
                                   '<div class="keybord_item">5</div>' +
                                   '<div class="keybord_item">6</div>' +
                                   '<div class="keybord_item">7</div>' +
                                   '<div class="keybord_item">8</div>' +
                                   ' <div class="keybord_item">9</div>' +
                                   '<div class="keybord_item">0</div>' +
                                   '<div id="keyborder_del">删除</div>' +
                                   '<div id="keyborder_empty">清空</div>' +
                               '</div>';
    }
    var content_html = '<div id="pregant">' +
                        '<div id="pregant_container">' +
                            ' <table>' +
                                '<tr>' +
                                    '<td style="width: 30%; padding: 10px 0; text-align:right;">当前孕周:</td>' +
                                    '<td>' +
                                        '<input type="text" name="当前孕周" id="pregant_week"/>' +
                                    '</td>' +
                                '</tr>' +
                                '<tr>' +
                                    '<td style="text-align:right;">孕周天数:</td>' +
                                    '<td>' +
                                        '<input type="text" name="孕周天数" id="pregant_day" />' +
                                    '</td>' +
                                ' </tr>' +
                            '</table>' +
                        '</div>' + keybord_html +
                    '</div>';
    //检查项目需要控制孕周，弹出输入框

    layer.open({
        type: 1,
        title: '孕期推算',
        skin: 'layui-layer-rim', //加上边框
        area: area, //宽高
        content: content_html,
        btn: ['确定', '取消'],
        no: function () {
            layer.closeAll();
            $('#keybord').hide();
        },
        yes: function () {
            var weeknum = $('#pregant_week').val();
            if (weeknum) {
                that.pregnantDays = parseInt(weeknum) * 7;
            }
            var days = $('#pregant_day').val();
            if (days) {
                that.pregnantDays += parseInt(days);
            }
            if(examRequest){ 
                examRequest.PregnantDays = that.pregnantDays;
            }
            if (callback) {
                callback();
            }
               
            layer.closeAll()
        },
        success: function (layero, index) {
            $('#pregant_week').focus();
            //输入数字 
            $('#keybord').on('click', '.keybord_item', function () {
                var thistext = $(this).text().trim();
                if (pregant_flag == 1) {
                    var oldVal = $('#pregant_week').val().trim();
                    if (oldVal == '' || oldVal == null || oldVal == "undefinded") {
                        if (thistext != 0) { $('#pregant_week').val(thistext); }

                    } else {
                        $('#pregant_week').val(oldVal + String(thistext));
                    }
                    $('#pregant_week').focus();
                } else {
                    var oldVal = $('#pregant_day').val().trim();
                    if (oldVal == '' || oldVal == null || oldVal == "undefinded") {
                        if (thistext != 0) {
                            $('#pregant_day').val(thistext);
                        }
                    } else {
                        $('#pregant_day').val(oldVal + String(thistext));
                    }
                    $('#pregant_day').focus();

                }
            });
            $('#pregant_week').click(function () { pregant_flag = 1; $('#pregant_week').focus(); });
            $('#pregant_day').click(function () { pregant_flag = 0; $('#pregant_day').focus(); });
            if (this.scheduleType == "Self") {
                //清空
                $('#keyborder_empty').click(function () {
                    if (pregant_flag) { $('#pregant_week').val(''); $('#pregant_week').focus(); } else { $('#pregant_day').focus(); $('#pregant_day').val('') }
                });
                //删除
                $('#keyborder_del').click(function () {
                    if (pregant_flag) {
                        var oldVal = $('#pregant_week').val().trim();
                        if (oldVal == '' || oldVal == null || oldVal == "undefinded") {
                            $('#pregant_week').val('');
                        } else {
                            $('#pregant_week').val(oldVal.substring(0, oldVal.length - 1));
                        }
                        $('#pregant_week').focus();
                    } else {
                        var oldVal = $('#pregant_day').val().trim();
                        if (oldVal == '' || oldVal == null || oldVal == "undefinded") {
                            $('#pregant_day').val('');
                        } else {
                            $('#pregant_day').val(oldVal.substring(0, oldVal.length - 1));
                        }
                        $('#pregant_day').focus();
                    }
                });
            }

        }
    });
};

//获取检查申请单列表
Schedule.prototype.getExamRequestList = function (callback, noDataCallback) {
    var that = this; 
    queryCondition = that.queryCondition; 
    var url = that.relativeUrl + "GetScheduleExamRequestList?scheduleType=" + that.scheduleType + "&detailView=" + (that.detailView || '');
    imcis.ajax(url, queryCondition, true, function (ret) {
        if (ret) {
            if (ret.success) {
                that.examRequestList = [];
                $.each(ret.resultList, function (i, n) {
                    if(n.ak && n.rk) {
                        var ak = imcis.rsa.decode(n.ak, n.rk);
                        n.Name = imcis.aes.decode(n.Name, ak);
                        n.PatientID =imcis.aes.decode(n.PatientID, ak);
                        n.AccessionNumber  =imcis.aes.decode(n.AccessionNumber, ak);
                        n.FillerOrderNO = imcis.aes.decode(n.FillerOrderNO, ak);
                        n.MedRecNO = imcis.aes.decode(n.MedRecNO, ak);
                        n.InPatientNO = imcis.aes.decode(n.InPatientNO, ak);
                        n.OutPatientNO = imcis.aes.decode(n.OutPatientNO, ak);
                        n.CardNO = imcis.aes.decode(n.CardNO, ak);
                        n.PlacerOrderNO = imcis.aes.decode(n.PlacerOrderNO, ak);
                        n.ContactPhoneNO = imcis.aes.decode(n.ContactPhoneNO, ak);
                        n.InsuranceID = imcis.aes.decode(n.InsuranceID, ak);
                        n.VisitID = imcis.aes.decode(n.VisitID, ak);
                        n.ProviderName = imcis.aes.decode(n.ProviderName, ak);
                        n.ProviderPhone = imcis.aes.decode(n.ProviderPhone, ak);
                        n.ProviderIDCardNO = imcis.aes.decode(n.ProviderIDCardNO, ak);
                        n.ScheduleOperatorID = imcis.aes.decode(n.ScheduleOperatorID, ak);
                        n.ScheduleOperatorName = imcis.aes.decode(n.ScheduleOperatorName, ak);
                        n.IDCardNO = imcis.aes.decode(n.IDCardNO, ak);
                        n.IdentityID = imcis.aes.decode(n.IdentityID, ak);
                        n.ProviderID = imcis.aes.decode(n.ProviderID, ak);
                        n.AddressDetail = imcis.aes.decode(n.AddressDetail, ak);
                    }
                    
                    if (n.ScheduleStatus == 0) {
                        n.ScheduleFlag = true;
                        n.ChangeFlag = false;
                        n.OriginalScheduleResourceName = n.ScheduleResourceName;
                        n.OriginalScheduleStartDate = n.ScheduleStartDate;
                        n.OriginalScheduleEndDate = n.ScheduleEndDate;
                    } else {
                        n.ScheduleFlag = false;
                    }
                    n = Schedule.transExamRequestDatetime(n);
                    n.ScheduleOperatorID = that.scheduleOperatorID;
                    n.ScheduleOperatorName = that.scheduleOperatorName;
                    if (n.ScheduleResource) {
                        if (n.ScheduleResource.ResourceLocation != undefined || n.ScheduleResource.ResourceLocation != null) {
                            n.ResourceLocation = n.ScheduleResource.ResourceLocation;
                        }
                        else {
                            n.ResourceLocation = "";
                        }
                    }
                    else {
                        n.ResourceLocation = "";
                    }
                   
                    if(n.GroupID){
                        var exist = false;
                        for (var i = 0; i <  that.examRequestList.length; i++) {
                            if(n.GroupID == that.examRequestList[i].GroupID) {
                                exist = true;
                                that.examRequestList[i].orderList.push(n);
                                that.examRequestList[i].PlacerOrderNO += ',' + n.PlacerOrderNO;
                                that.examRequestList[i].ProcedureID += ',' + n.ProcedureID;
                                that.examRequestList[i].ProcedureName += ',' + n.ProcedureName;
                                
                                if(that.examRequestList[i].AccessionNumber.indexOf(n.AccessionNumber) == -1){
                                    that.examRequestList[i].AccessionNumber += ',' + n.AccessionNumber;
                                }

                                break;
                            }
                        }

                        if(!exist) {
                            var mergeOrder = {
                                Name: n.Name,
                                OutPatientNO: n.OutPatientNO,
                                InPatientNO: n.InPatientNO,
                                ContactPhoneNO: n.ContactPhoneNO,
                                ProviderName: n.ProviderName,
                                PregnantDays: n.PregnantDays,
                                MedRecNO: n.MedRecNO,
                                PlacerOrderNO: n.PlacerOrderNO,
                                PlacerAssigningAuthority: n.PlacerAssigningAuthority,
                                OrganizationID: n.OrganizationID,
                                ServiceSectID: n.ServiceSectID,
                                ProcedureName: n.ProcedureName,
                                ProcedureID: n.ProcedureID,
                                ServiceText: n.ServiceText,
                                PatientClass: n.PatientClass,
                                PatientType: n.PatientType,
                                TransportationMode: n.TransportationMode,
                                PointOfCare: n.PointOfCare,
                                RequestedDate: n.RequestedDate,
                                FastingFlag: n.FastingFlag,
                                ScheduleFlag: n.ScheduleFlag,
                                ObservationUID: n.ObservationUID,
                                RequestDeptID: n.RequestDeptID,
                                RequestDeptName: n.RequestDeptName,
                                SelfScheduleFlag: n.SelfScheduleFlag,
                                NeedScheduleFlag: n.NeedScheduleFlag,
                                GroupID: n.GroupID,
                                ResultStatus: n.ResultStatus,
                                ScheduleStartDate:n.ScheduleStartDate,
                                ScheduleEndDate:n.ScheduleEndDate,
                                ScheduleID:n.ScheduleID,
                                ResourceLocation:n.ResourceLocation,
                                ScheduleNotice:n.ScheduleNotice,
                                ScheduleResource: n.ScheduleResource,
                                ReceiptPrintCount: n.ReceiptPrintCount,
                                AccessionNumber: (n.AccessionNumber || '')
                            };
                            mergeOrder.orderList = [];
                            mergeOrder.orderList.push(n);
                            that.examRequestList.push(mergeOrder);
                        }
                    } else {
                        that.examRequestList.push(n);
                    }
                });

                $.each(that.examRequestList, function (i, n) { 
                    if(n.GroupID) {
                        n.GroupCount = n.orderList.length;
                    }
                });

                if (callback) {
                    callback(that.examRequestList);
                }
            } else {
                if(noDataCallback){
                    noDataCallback(ret.errorMsg);
                } else {
                    that.alert(ret.errorMsg);
                }
            }
        } else {
            that.alert("查询检查申请单失败，请重试。");
        }
    });
};

//获取检查申请单列表并推荐预约
Schedule.prototype.getExamRequestScheduleInfoList = function (callback) {
    var that = this;
    var url = that.relativeUrl + "GetScheduleInfoListWithExamRequest?scheduleType=" + that.scheduleType + "&pregnantDays=" + that.pregnantDays;

    imcis.ajax(url, that.queryCondition, true, function (ret) {
        if (ret) {
            if (ret.needPregnantDays) {
                //显示孕周对话框，输入孕周天数
                that.showPregnantDays(function(){
                    that.getExamRequestScheduleInfoList(callback);
                });

                return;
            }

            if (ret.success) {
                that.examRequestList = ret.resultList;

                $.each(that.examRequestList, function (i, n) {
                    if (n.ScheduleStatus == 0) {
                        n.ScheduleFlag = true;
                    } else {
                        n.ScheduleFlag = false;
                    }
                    n = Schedule.transExamRequestDatetime(n);
                });

                if (ret.errorMsg) {
                    that.alert(ret.errorMsg);
                }

                if (callback) {
                    callback(that.examRequestList);
                }
            } else {
                that.alert(ret.errorMsg);
            }
        } else {
            that.alert("查询检查申请单失败，请重试!");
        }
    });
};

//获取病人检查申请单
Schedule.prototype.getPatientExamRequestList = function (callback) {
    var that = this;
    var url = that.relativeUrl + "GetPatientExamRequestList?scheduleType=" + that.scheduleType;
    imcis.ajax(url, that.queryCondition, true, function (ret) {
        if (ret) {
            if (ret.success) {
                that.patientList = ret.resultList;
                $.each(that.patientList, function (i, m) {
                    $.each(m.ExamRequestList, function(j, n){
                        if (n.ScheduleStatus == 0 || !!n.ScheduleResourceName && !!n.ScheduleStartDate && !!n.ScheduleEndDate) {
                            n.ScheduleFlag = true;
                            n.ChangeFlag = false;
                            n.OriginalScheduleResourceName = n.ScheduleResourceName;
                            n.OriginalScheduleStartDate = n.ScheduleStartDate;
                            n.OriginalScheduleEndDate = n.ScheduleEndDate;
                        } else {
                            n.ScheduleFlag = false;
                        }
                        n = Schedule.transExamRequestDatetime(n);
                    });
                });

                if (callback) {
                    callback(that.patientList);
                }
            } else {
                that.alert(ret.errorMsg);
                $('.center_left_container').html('');
                $('.center_right').hide();
            }
        } else {
            that.alert("查询检查申请单失败，请重试。");
        }
    });
};

//获取单个检查申请单的预约推荐信息
Schedule.prototype.getScheduleInfo = function (examRequest, relateExamRequestList, resourceUID, doctorName, getRemainNumberFlag, callback, errcallback) {
    var data = examRequest;
    data.ResourceUID = resourceUID;
    data.StartDate = this.startDate;
    data.Days = this.days;
    data.DoctorName = doctorName || "";
    data.ExamRequestScheduleArrageInfoList = [];
    data.IgnoreScheduleFlag = this.IgnoreScheduleFlag;

    $.each(relateExamRequestList, function (i, n) {
        data.ExamRequestScheduleArrageInfoList.push({
            ServiceSectID: n.ServiceSectID,
            ServiceText: n.ServiceText,
            ProcedureName: n.ProcedureName,
            ProcedureID: n.ProcedureID,
            ScheduleDate: n.ScheduleStartDate.substring(0, 10),
            ScheduleTime: n.ScheduleStartDate.substr(11, 5) + "-" + n.ScheduleEndDate.substr(11, 5)
        });
    });

    var url = this.relativeUrl + "GetScheduleInfo";
    var that = this;

    imcis.ajax(url, data, true, function (ret) {
        if (ret) {
            if (ret.needPregnantDays) {
                //显示孕周对话框，输入孕周天数
                that.showPregnantDays(function(){
                    that.getScheduleInfo(examRequest, relateExamRequestList, resourceUID, doctorName, getRemainNumberFlag, callback, errcallback);
                }, examRequest);

                return;
            }
            if (ret.success) {
                if (ret.errorMsg) {
                    that.alert(ret.errorMsg);
                    if (errcallback) {
                        errcallback(ret.result);
                    }
                }

                if (callback) {
                    callback(ret.result, getRemainNumberFlag);
                }
            } else {
                that.alert(ret.errorMsg);
                if (errcallback) {
                    errcallback(ret.result);
                }
            }
        } else {
            that.alert("查询预约推荐信息失败，请重试!");
            if (errcallback) {
                errcallback();
            }
        }
    });
};

//打印预约回执单
Schedule.prototype.print = function (examRequest, page) {
    var that = this;
    that.loading();
    var url = that.relativeUrl + "GetPrintExamScheduleReceipt";
    imcis.ajax(url, {
        placerOrderNO: examRequest.PlacerOrderNO,
        observationUID: examRequest.ObservationUID
    }, true, function (ret) {
        if (ret) {
            var lodop = getPrint();
            if ($.trim(PrinterName) || ret.page) {
                lodop.setDefault(PrinterName, ret.page);
            } else {
                lodop.setDefault();
            }

            var customSize = imcis.cookie.getConfig('scheduleReceiptPrintCustomSize');
            if (customSize && customSize != "0") {
                lodop.print('base64', ret.image, $("#hfplugin").val(), ret.width, ret.height);
                if(ret.imageOther && ret.imageOther.length > 0) {
                    for (var m = 0; m < ret.imageOther.length; m++) {
                        lodop.print('base64', ret.imageOther[m], $("#hfplugin").val(), ret.width, ret.height);
                    }
                }
            } else {
                 lodop.print('base64', ret.image, $("#hfplugin").val());
                 if(ret.imageOther && ret.imageOther.length > 0) {
                    for (var m = 0; m < ret.imageOther.length; m++) {
                        lodop.print('base64', ret.imageOther[m], $("#hfplugin").val());
                    }
                }
            }

            imcis.ajax(that.relativeUrl + "PrintFinish", {
                placerOrderNO: examRequest.PlacerOrderNO,
                observationUID: examRequest.ObservationUID,
                scheduleOperatorID: this.scheduleOperatorID,
                scheduleOperatorName: this.scheduleOperatorName
            }, true, function () {
                $('.pull-left[data-placerorderno=' + examRequest.PlacerOrderNO + ']').find('.print_img').removeClass('print_img_check').addClass('print_img_cancel');
                examRequest.printFlag = !examRequest.printFlag;
                examRequest.ReceiptPrintCount++;
                page.printTotal--;
                $('#print').text('打印预约单' + (page.printTotal === 0 ? "" : "（" + page.printTotal + "）"));
                that.removeLoading();
                if (page.printTotal === 0) {
                    that.alert('打印成功，请取走回执单!(<span id="layui-layer-content-time">3</span>秒后自动关闭)');
                    var timer = setInterval(function () {
                        var time = $("#layui-layer-content-time").text();
                        time--;
                        $("#layui-layer-content-time").text(time);
                        if (time <= 0) {
                            layer.closeAll('dialog');
                            clearInterval(timer);
                        }
                    }, 1000);
                }
            });
        }
    });
};

//取消预约
Schedule.prototype.cancelSchedule = function (examRequest, callback) {
    var data = {
        PlacerOrderNO: examRequest.PlacerOrderNO,
        ScheduleOperatorID: this.scheduleOperatorID,
        ScheduleOperatorName: this.scheduleOperatorName,
        ScheduleRoute: examRequest.ScheduleRoute,
        ScheduleBreakFlag: examRequest.ScheduleBreakFlag ? 1 : 0,
        OrganizationID: examRequest.OrganizationID
    };
    var that = this;
    //提示是否取消预约
    imcis.ajax(this.relativeUrl + "CancelExamSchedule", data, true, function (ret) {
        if (ret && ret.success) {
            
            if (callback) {
                callback();
            }
            imcis.wait.end();
        } else {
            that.alert(ret.errorMsg);
        }
    });
};

//保存预约
Schedule.prototype.saveExamSchedule = function (examRequest, scheduleBreakFlag, callback, completeFn) {
    var examRequestList = [];
    var saveList = [];
    var that = this;
    if (examRequest) {
        if(examRequest.GroupID && examRequest.orderList.length > 0){
            for (var i = 0; i < examRequest.orderList.length; i++) {
                examRequest.orderList[i].ScheduleResourceUID = examRequest.ScheduleResourceUID;
                examRequest.orderList[i].ScheduleResourceName = examRequest.ScheduleResourceName;
                examRequest.orderList[i].ObservationLocation = examRequest.ObservationLocation;
                examRequest.orderList[i].ScheduleStartDate = examRequest.ScheduleStartDate;
                examRequest.orderList[i].ScheduleEndDate = examRequest.ScheduleEndDate;
                examRequest.orderList[i].ChangeFlag = examRequest.ChangeFlag;
                examRequest.orderList[i].OccupyNumber = examRequest.OccupyNumber;

                examRequestList.push(examRequest.orderList[i]);
            }
        }else{
            examRequestList.push(examRequest);
        }
    } else {
        examRequestList = that.examRequestList;
    }
    $.each(examRequestList, function (i, n) {
        n.ScheduleOperatorID = that.scheduleOperatorID;
        n.ScheduleOperatorName = that.scheduleOperatorName;
        if (n.ScheduleStartDate && n.ScheduleEndDate && ((n.ScheduleFlag && n.ChangeFlag) || !n.ScheduleFlag)) {
            var info = {
                ScheduleResourceUID: n.ResourceUID || n.ScheduleResourceUID,
                ScheduleResourceName: n.ResourceName || n.ScheduleResourceName,
                ScheduleDate: n.ScheduleDate || n.ScheduleStartDate.split(' ')[0],
                StartTime: n.ScheduleTime ? n.ScheduleTime.split('-')[0] : n.ScheduleStartDate.split(' ')[1],
                EndTime: n.ScheduleTime ? n.ScheduleTime.split('-')[1] : n.ScheduleEndDate.split(' ')[1],
                Quantity: n.Quantity,
                ScheduleOperatorID: that.scheduleOperatorID,
                ScheduleOperatorName: that.scheduleOperatorName,
                OrganizationID: n.OrganizationID,
                PlacerOrderNO: n.PlacerOrderNO,
                PlacerAssigningAuthority: n.PlacerAssigningAuthority,
                Name: n.Name,
                ContactPhoneNO: n.ContactPhoneNO,
                ServiceSectID: n.ServiceSectID,
                ServiceText: n.ServiceText,
                ProcedureName: n.ProcedureName,
                PatientClass: n.PatientClass,
                MedRecNO: n.MedRecNO,
                ScheduleFlag: n.ScheduleFlag,
                GroupID: n.GroupID,
                ScheduleRoute: n.ScheduleRoute,
                OccupyNumber: n.OccupyNumber
            };
            
            saveList.push({
                ScheduleRequestInfo: info,
                ExamRequest: n
            });
        }
    });

    var url = that.relativeUrl + "SaveExamSchedule?t=" + imcis.date.now();
    imcis.ajax(url, { scheduleRequestList: saveList, scheduleBreakFlag: scheduleBreakFlag ? 1 : 0}, true,
        function (ret) {
            if (ret.failMsgList && ret.failMsgList.length > 0) {
                var errorMsg = ret.failMsgList.join(',');
                that.alert(errorMsg);
            }
            if (ret.successMsg) {
                that.alert(ret.successMsg);
            }

            if(ret.writebackFailList && ret.writebackFailList.length > 0) {
                that.alert("保存预约回写失败，请到服务台处理。");
            }

            var successList = [];
            if (ret.successList && ret.successList.length > 0) {
                $.each(ret.successList, function (i, n) {
                    $.each(that.examRequestList, function (j, m) {
                        if (n.PlacerOrderNO == m.PlacerOrderNO) {
                            m.ObservationUID = n.ObservationUID;
                            m.ResourceLocation = n.ResourceLocation;
                            m.ScheduleResourceUID = n.ScheduleResourceUID;
                            m.ScheduleResourceName = n.ScheduleResourceName;
                            m.ScheduleStartDate = n.ScheduleDate + " " + n.StartTime;
                            m.ScheduleEndDate = n.ScheduleDate + " " + n.EndTime;
                            m.ScheduleTimeDetail = n.ScheduleTimeDetail;
                            m.ScheduleStartTimeDetail = n.ScheduleStartTimeDetail;
                            m.ScheduleEndTimeDetail = n.ScheduleEndTimeDetail;
                            m.ScheduleNotice = n.ScheduleNotice;
                            m.ScheduleID =  n.ScheduleID;
                            m.ScheduleFlag = true;
                            
                            successList.push(m);
                            return false;
                        } else if( m.PlacerOrderNO.indexOf(n.PlacerOrderNO) > -1) {
                            var existGroup = false;
                            for (var k = 0; k < successList.length; k++) {
                                if(successList[k].PlacerOrderNO.indexOf(n.PlacerOrderNO)> -1){
                                    m.ScheduleNotice += n.ScheduleNotice;
                                    existGroup = true;
                                    break;
                                }
                            }

                            if (!existGroup) {
                                m.ObservationUID = n.ObservationUID;
                                m.ResourceLocation = n.ResourceLocation;
                                m.ScheduleResourceUID = n.ScheduleResourceUID;
                                m.ScheduleResourceName = n.ScheduleResourceName;
                                m.ScheduleStartDate = n.ScheduleDate + " " + n.StartTime;
                                m.ScheduleEndDate = n.ScheduleDate + " " + n.EndTime;
                                m.ScheduleTimeDetail = n.ScheduleTimeDetail;
                                m.ScheduleStartTimeDetail = n.ScheduleStartTimeDetail;
                                m.ScheduleEndTimeDetail = n.ScheduleEndTimeDetail;
                                m.ScheduleNotice = n.ScheduleNotice;
                                m.ScheduleID =  n.ScheduleID;
                                m.ScheduleFlag = true;
                                successList.push(m);
                                return false;
                            }
                        }
                    });
                    
                });
            }

            if (callback) {
                callback(successList, ret.writebackFailList); 
            }
        },'','',completeFn);
};
//根据SelfPrintReceipt和PrintExamScheduleReceiptAfterAutoSave判断自助预约保存后是否立即打印
Schedule.prototype.printAfterAutoSave = function (examRequest,page) {
    var that = this;
    if ($.trim(SelfPrintReceipt) != '0' && that.judgingExamRequestMatchSysParameter(examRequest, PrintExamScheduleReceiptAfterAutoSave,"自助预约打印参数"))
    {
        try {
            that.print(examRequest, page);
        } catch (e) {}
        
    } else
    {
        //SelfPrintReceipt=='0'保存后不打印
    }
    
};
//根据sysParameter(保存打印参数和签到参数)判断examRequest是否符合其规则
Schedule.prototype.judgingExamRequestMatchSysParameter = function (examRequest, sysParameter, parameterName) {
    var that = this;
    sysParameter = $.trim(sysParameter)
    if (sysParameter == "" || sysParameter == "0") {
        return false;
    } else if (sysParameter == "1") {
        return true;
    } else {
        var printRule = sysParameter.split("|");
        for (var i = 0; i < printRule.length; i++) {
            var value = printRule[i].split("=");
            if (value.length == 2) {
                if (value[0].indexOf('+') > -1 && value[0].indexOf(examRequest.ServiceSectID)>-1 && value[0].indexOf(examRequest.PatientClass)>-1 && value[1] == '1') {
                    return true;
                } 
            } else {
                that.alert(parameterName + "设置有误！");
                return false;
            }
        }
        for (var i = 0; i < printRule.length; i++) {
            var value = printRule[i].split("=");
            if (value.length == 2) {
                if (value[0] == examRequest.ServiceSectID) {
                    switch ($.trim(value[1])) {
                        case "1":
                            return true;
                        case "0":
                            return false;
                        case n.PatientClass:
                            return true;
                        default:
                            return false;
                    }
                } 
            } else {
                that.alert(parameterName + "设置有误！");
                return false;
            }
        }
        return false
    }
};
//根据sysParameter（预约时间前多少分钟不允许自助取消或自助修改）
Schedule.prototype.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead = function (n,sysParameter) {
    var that = this;
    var sysParameterValue = that.GetSysParameterValueByExamRequest(n, sysParameter);
    if (sysParameterValue == "" || n.ScheduleStartDate == null) {//参数值为空允许
        return true;
    }
    if (!isNaN(sysParameterValue)) {//sysParameterValue为数字
        var todayDate = new Date();
        var scheduleTime = new Date(Date.parse(n.ScheduleStartDate.replace(/-/g, "/")));
        //过了预约时间则不需要根据参数判断，可以进行操作
        if (todayDate > scheduleTime) {
            return true;
        }
        todayDate.setTime(todayDate.getTime() + 1000 * 60 * sysParameterValue);
        if (todayDate > scheduleTime)//当前时间+系统设置时间参数大于预约时间，则不允许修改或取消
        {
            return false;
        } else {//当前时间+系统设置时间参数小于或等于预约时间，则允许修改或取消
        }
    } else {//不为数字,允许修改
    }
    return true;
}
//根据根据检查类型获取参数值
Schedule.prototype.GetSysParameterValueByExamRequest = function (examRequest, sysParameter) {
    sysParameter = $.trim(sysParameter);
    if (sysParameter == "") {//sysParameter为空
        return "";//都允许
    } else {
        var parameterArray = sysParameter.split('|');
        if (parameterArray.length == 1) {
            var parameterArraySplit = parameterArray[0].split("=");
            if (parameterArraySplit.length == 1) {//参数为一个值的形式，如"30"
                return parameterArraySplit[0];
            } else if (examRequest.ServiceSectID == parameterArraySplit[0]) {//参数为：“CT=1”形式；
                return parameterArraySplit[1];
            } else if(examRequest.PatientClass == parameterArraySplit[0]){//参数为：“门诊=1”形式；
                return parameterArraySplit[1];
            } else if (parameterArraySplit[0].indexOf('+') > -1 && parameterArraySplit[0].indexOf(examRequest.ServiceSectID) > -1 && parameterArraySplit[0].indexOf(examRequest.PatientClass) > -1) {
                return parameterArraySplit[1];
            } else {
                return "";
            }
        } else {//参数为：CT=20|MR=45|RF=69|门诊=1|RF+门诊=69形式
            for (var i = 0; i < parameterArray.length; i++) {
                var parameterArraySplit = parameterArray[i].split("=");
                if (parameterArraySplit[0].indexOf('+') > -1 && parameterArraySplit[0].indexOf(examRequest.ServiceSectID) > -1 && parameterArraySplit[0].indexOf(examRequest.PatientClass) > -1) {
                    return parameterArraySplit[1];
                }
            }
            for (var i = 0; i < parameterArray.length; i++) {
                var parameterArraySplit = parameterArray[i].split("=");
                if (examRequest.ServiceSectID == parameterArraySplit[0]) {
                    return parameterArraySplit[1];
                }
            }
            for (var i = 0; i < parameterArray.length; i++) {
                var parameterArraySplit = parameterArray[i].split("=");
                if (examRequest.PatientClass == parameterArraySplit[0]) {
                    return parameterArraySplit[1];
                }
            }
        }
    }
    return "";//参数不为空，根据申请单没有找到相应参数
}

//根据预约路径、检查类型、就诊类型获取参数值
Schedule.prototype.GetSysParameterValueByExamRequest2 = function (examRequest, sysParameter) {
    sysParameter = $.trim(sysParameter);
    if (sysParameter == "") {//sysParameter为空
        return "";
    } else if (sysParameter.indexOf("=") == -1) {//参数为：“69”形式；
        return sysParameter;
    } else {
        var scheduleRoute = examRequest.ScheduleRoute == "5" ? "手机端" : "自助机";
        var parameterArray = sysParameter.split('|');

        for (var i = 0; i < parameterArray.length; i++) {
            var parameterArraySplit = parameterArray[i].split("=");
            var keyLen = parameterArraySplit[0].split('+').length; //参数key组成个数
            switch (keyLen) {
                case 1:
                    //参数为：“手机端=1”、“CT=1”、“门诊=1”形式；
                    if (scheduleRoute == parameterArraySplit[0] || examRequest.ServiceSectID == parameterArraySplit[0] || examRequest.PatientClass == parameterArraySplit[0]) {
                        return parameterArraySplit[1];
                    }
                    break;
                case 2:
                    if (parameterArraySplit[0].indexOf(scheduleRoute) > -1 && parameterArraySplit[0].indexOf(examRequest.ServiceSectID) > -1) {//自助机+RF=69
                        return parameterArraySplit[1];
                    }
                    if (parameterArraySplit[0].indexOf(scheduleRoute) > -1 && parameterArraySplit[0].indexOf(examRequest.PatientClass) > -1) {//自助机+门诊=69
                        return parameterArraySplit[1];
                    }
                    if (parameterArraySplit[0].indexOf(examRequest.ServiceSectID) > -1 && parameterArraySplit[0].indexOf(examRequest.PatientClass) > -1) {//RF+门诊=69
                        return parameterArraySplit[1];
                    }
                    break;
                case 3:
                    if (parameterArraySplit[0].indexOf(scheduleRoute) > -1 && parameterArraySplit[0].indexOf(examRequest.ServiceSectID) > -1 && parameterArraySplit[0].indexOf(examRequest.PatientClass) > -1) { //自助机+RF+门诊=69
                        return parameterArraySplit[1];
                    }
                    break;
            }
        }
    }
    return "";
}

//根据参数值获取时间
Schedule.prototype.GetDateByExamAndParam = function (exam, param) {
    var dateStr = exam.ScheduleStartDate;//默认预约开始时间
    param = (!isNaN(param) && param.indexOf("-") == -1 ? "+" : "") + param;
    var symbols = param.indexOf("-") > -1 ? "-" : "";
    param = param.replace("+", "$").replace("-", "$");
    var paramArr = param.split("$");
    var fileValue = 0;
    if (paramArr.length > 1) {
        dateStr = paramArr[0] == "" || exam[paramArr[0]] == null ? dateStr : imcis.convertDateFromJson(exam[paramArr[0]]);
        fileValue = parseFloat(symbols + (paramArr[1] == "" ? 0 : paramArr[1]));
    } else {
        fileValue = parseFloat(symbols + (paramArr[0] == "" ? 0 : paramArr[0]));
    }
    dateStr = dateStr.replace(/-/g, ':').replace(' ', ':');
    dateStr = dateStr.split(':');
    var dateValue = new Date(dateStr[0], (dateStr[1] - 1), dateStr[2], dateStr[3], dateStr[4], '00');
    //字段数据加减参数设置值 object instanceof Date
    dateValue.setMinutes(dateValue.getMinutes() + fileValue);
    //时间转指定格式字符串  imcis.date.dateStringFromDate(dateValue)
    var dateStr = dateValue.Format("yyyy-MM-dd hh:mm");
    dateStr = (typeof dateStr == "undefined" || dateStr == "null") ? "" : dateStr
    return dateStr;
}

//检查是否被黑名单限制
Schedule.prototype.CheckPatientLimit = function (param, callback) {
    var that = this; 
    imcis.ajax(that.relativeUrl + "CheckExamRequestLimit", param, false, function (ret) {
        if(ret) {
            if (callback) 
                callback(ret);
        }
    });
}

/*
//保存黑名单
Schedule.prototype.saveScheduleBlacklist = function (examRequest, callback) {
    var that = this;
    imcis.ajax(this.relativeUrl + "SaveScheduleBlacklist", examRequest, true, function (ret) {
        if (ret && ret.success) {
            if (callback) {
                callback();
            }
        } else {
            that.alert(ret.errorMsg);
        }
    });
};
*/